// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const userCollection = db.collection('user')
const cmtCollection = db.collection('comment')
const rightCollection = db.collection('right')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const voiceId = event.voiceId
  const authorId = event.authorId
  const page = event.page || 1
  const pageSize = event.pageSize || 10
  const currentPage = (page - 1) * pageSize

  let commentList = []
  if (authorId == wxContext.OPENID){
  await  cmtCollection.where({
      voiceId
  }).skip(currentPage).limit(pageSize).orderBy('commentDate', 'desc').get().then(res => {
      commentList = res.data
    })
  }else{
  await  cmtCollection.where({
      voiceId,
      commentatorId: wxContext.OPENID
    }).get().then(res => {
      commentList = res.data
    })
  }

  for (let item of commentList) {
    await userCollection.where({
      _openid: item.commentatorId
    }).get().then(res => {
      item.commentatorInfo = res.data[0]
    })
    await rightCollection.where({
      righter: item.commentatorId,
      righted: wxContext.OPENID,
      status: 2
    }).get().then(res => {
      if(res.data.length == 0){
        item.isRight = false
      }else{
        item.isRight = true
      }
    })
    if (!item.isRight){
      await rightCollection.where({
        righter: wxContext.OPENID,
        righted: item.commentatorId,
        status: 2
      }).get().then(res => {
        if (res.data.length == 0) {
          item.isRight = false
        } else {
          item.isRight = true
        }
      })
    }
  }
  
  return commentList
}